<template>
  <div class="report-container">
    <div class="page-header">
      <h2 class="page-title">统计报表</h2>
    </div>
    
    <!-- 过滤条件 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="业务类型">
          <el-select v-model="filterForm.businessTypeId" placeholder="请选择业务类型" clearable>
            <el-option
              v-for="item in businessTypes"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="窗口">
          <el-select v-model="filterForm.windowId" placeholder="请选择窗口" clearable>
            <el-option
              v-for="item in windows"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetFilter">重置</el-button>
          <el-button type="success" @click="exportExcel">
            <el-icon><Download /></el-icon>导出Excel
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>总取号人数</span>
              </div>
            </template>
            <div class="card-value">{{ summaryData.totalTickets || 0 }}</div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>已服务人数</span>
              </div>
            </template>
            <div class="card-value">{{ summaryData.servedTickets || 0 }}</div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>未服务人数</span>
              </div>
            </template>
            <div class="card-value">{{ summaryData.unservedTickets || 0 }}</div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>平均等待时间</span>
              </div>
            </template>
            <div class="card-value">{{ formatTime(summaryData.avgWaitTime) }}</div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 趋势图表 -->
    <div class="charts-container">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="card-header">
                <span>每日取号人数趋势</span>
                <el-radio-group v-model="chartType" size="small">
                  <el-radio-button label="day">日视图</el-radio-button>
                  <el-radio-button label="week">周视图</el-radio-button>
                  <el-radio-button label="month">月视图</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div ref="ticketTrendChart" class="chart"></div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" class="mt-20">
        <el-col :span="12">
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="card-header">
                <span>业务类型分布</span>
              </div>
            </template>
            <div ref="businessTypeChart" class="chart"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="card-header">
                <span>等待时间统计</span>
              </div>
            </template>
            <div ref="waitTimeChart" class="chart"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 详细数据表格 -->
    <div class="data-table-container">
      <el-card shadow="hover">
        <template #header>
          <div class="card-header">
            <span>详细数据</span>
          </div>
        </template>
        <el-tabs v-model="activeTab">
          <el-tab-pane label="日期统计" name="daily">
            <el-table :data="dailyData" border style="width: 100%" v-loading="tableLoading">
              <el-table-column prop="date" label="日期" width="120" />
              <el-table-column prop="totalTickets" label="取号人数" width="100" />
              <el-table-column prop="servedTickets" label="已服务人数" width="120" />
              <el-table-column prop="unservedTickets" label="未服务人数" width="120" />
              <el-table-column prop="avgWaitTime" label="平均等待时间">
                <template #default="scope">
                  {{ formatTime(scope.row.avgWaitTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="avgServiceTime" label="平均服务时间">
                <template #default="scope">
                  {{ formatTime(scope.row.avgServiceTime) }}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="业务类型统计" name="businessType">
            <el-table :data="businessTypeData" border style="width: 100%" v-loading="tableLoading">
              <el-table-column prop="businessTypeName" label="业务类型" min-width="150" />
              <el-table-column prop="totalTickets" label="取号人数" width="100" />
              <el-table-column prop="servedTickets" label="已服务人数" width="120" />
              <el-table-column prop="unservedTickets" label="未服务人数" width="120" />
              <el-table-column prop="avgWaitTime" label="平均等待时间">
                <template #default="scope">
                  {{ formatTime(scope.row.avgWaitTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="avgServiceTime" label="平均服务时间">
                <template #default="scope">
                  {{ formatTime(scope.row.avgServiceTime) }}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="窗口统计" name="window">
            <el-table :data="windowData" border style="width: 100%" v-loading="tableLoading">
              <el-table-column prop="windowName" label="窗口名称" min-width="150" />
              <el-table-column prop="staffName" label="工作人员" width="120" />
              <el-table-column prop="totalServed" label="服务人数" width="100" />
              <el-table-column prop="avgServiceTime" label="平均服务时间">
                <template #default="scope">
                  {{ formatTime(scope.row.avgServiceTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="totalServiceTime" label="总服务时间">
                <template #default="scope">
                  {{ formatTime(scope.row.totalServiceTime) }}
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:currentPage="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Download } from '@element-plus/icons-vue'
import axios from 'axios'
import * as echarts from 'echarts'

export default {
  name: 'StatisticsReport',
  components: {
    Search,
    Download
  },
  setup() {
    // 图表引用
    const ticketTrendChart = ref(null)
    const businessTypeChart = ref(null)
    const waitTimeChart = ref(null)
    
    // 图表实例
    let ticketTrendChartInstance = null
    let businessTypeChartInstance = null
    let waitTimeChartInstance = null
    
    // 获取业务类型和窗口列表
    const businessTypes = ref([])
    const windows = ref([])
    
    // 过滤表单
    const filterForm = reactive({
      dateRange: [
        new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        new Date().toISOString().split('T')[0]
      ],
      businessTypeId: '',
      windowId: ''
    })
    
    // 图表类型
    const chartType = ref('day')
    
    // 表格活动标签
    const activeTab = ref('daily')
    
    // 表格数据
    const summaryData = ref({})
    const dailyData = ref([])
    const businessTypeData = ref([])
    const windowData = ref([])
    const tableLoading = ref(false)
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 获取业务类型列表
    const fetchBusinessTypes = () => {
      axios.get('/api/admin/business-types', { params: { limit: 100 } })
        .then(res => {
          if (res.data.code === 0) {
            businessTypes.value = res.data.data.list
          } else {
            ElMessage.error(res.data.msg || '获取业务类型列表失败')
          }
        })
        .catch(err => {
          console.error('获取业务类型列表失败:', err)
          ElMessage.error('获取业务类型列表失败')
        })
    }
    
    // 获取窗口列表
    const fetchWindows = () => {
      axios.get('/api/admin/windows', { params: { limit: 100 } })
        .then(res => {
          if (res.data.code === 0) {
            windows.value = res.data.data.list
          } else {
            ElMessage.error(res.data.msg || '获取窗口列表失败')
          }
        })
        .catch(err => {
          console.error('获取窗口列表失败:', err)
          ElMessage.error('获取窗口列表失败')
        })
    }
    
    // 格式化时间
    const formatTime = (seconds) => {
      if (!seconds && seconds !== 0) return '0分0秒'
      
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = Math.floor(seconds % 60)
      
      if (minutes > 0) {
        return `${minutes}分${remainingSeconds}秒`
      } else {
        return `${remainingSeconds}秒`
      }
    }
    
    // 获取统计数据摘要
    const fetchSummaryData = () => {
      const params = {
        startDate: filterForm.dateRange[0],
        endDate: filterForm.dateRange[1],
        businessTypeId: filterForm.businessTypeId || undefined,
        windowId: filterForm.windowId || undefined
      }
      
      axios.get('/api/admin/statistics/summary', { params })
        .then(res => {
          if (res.data.code === 0) {
            summaryData.value = res.data.data
          } else {
            ElMessage.error(res.data.msg || '获取统计摘要失败')
          }
        })
        .catch(err => {
          console.error('获取统计摘要失败:', err)
          ElMessage.error('获取统计摘要失败')
        })
    }
    
    // 获取每日统计数据
    const fetchDailyData = () => {
      tableLoading.value = true
      
      const params = {
        startDate: filterForm.dateRange[0],
        endDate: filterForm.dateRange[1],
        businessTypeId: filterForm.businessTypeId || undefined,
        windowId: filterForm.windowId || undefined,
        page: pagination.currentPage,
        limit: pagination.pageSize
      }
      
      axios.get('/api/admin/statistics/daily', { params })
        .then(res => {
          tableLoading.value = false
          if (res.data.code === 0) {
            dailyData.value = res.data.data.list
            pagination.total = res.data.data.total
          } else {
            ElMessage.error(res.data.msg || '获取每日统计数据失败')
          }
        })
        .catch(err => {
          tableLoading.value = false
          console.error('获取每日统计数据失败:', err)
          ElMessage.error('获取每日统计数据失败')
        })
    }
    
    // 获取业务类型统计数据
    const fetchBusinessTypeData = () => {
      tableLoading.value = true
      
      const params = {
        startDate: filterForm.dateRange[0],
        endDate: filterForm.dateRange[1],
        businessTypeId: filterForm.businessTypeId || undefined,
        windowId: filterForm.windowId || undefined,
        page: pagination.currentPage,
        limit: pagination.pageSize
      }
      
      axios.get('/api/admin/statistics/business-type', { params })
        .then(res => {
          tableLoading.value = false
          if (res.data.code === 0) {
            businessTypeData.value = res.data.data.list
            pagination.total = res.data.data.total
          } else {
            ElMessage.error(res.data.msg || '获取业务类型统计数据失败')
          }
        })
        .catch(err => {
          tableLoading.value = false
          console.error('获取业务类型统计数据失败:', err)
          ElMessage.error('获取业务类型统计数据失败')
        })
    }
    
    // 获取窗口统计数据
    const fetchWindowData = () => {
      tableLoading.value = true
      
      const params = {
        startDate: filterForm.dateRange[0],
        endDate: filterForm.dateRange[1],
        businessTypeId: filterForm.businessTypeId || undefined,
        windowId: filterForm.windowId || undefined,
        page: pagination.currentPage,
        limit: pagination.pageSize
      }
      
      axios.get('/api/admin/statistics/window', { params })
        .then(res => {
          tableLoading.value = false
          if (res.data.code === 0) {
            windowData.value = res.data.data.list
            pagination.total = res.data.data.total
          } else {
            ElMessage.error(res.data.msg || '获取窗口统计数据失败')
          }
        })
        .catch(err => {
          tableLoading.value = false
          console.error('获取窗口统计数据失败:', err)
          ElMessage.error('获取窗口统计数据失败')
        })
    }
    
    // 获取趋势图数据
    const fetchTrendData = () => {
      const params = {
        startDate: filterForm.dateRange[0],
        endDate: filterForm.dateRange[1],
        businessTypeId: filterForm.businessTypeId || undefined,
        windowId: filterForm.windowId || undefined,
        type: chartType.value
      }
      
      axios.get('/api/admin/statistics/trend', { params })
        .then(res => {
          if (res.data.code === 0) {
            renderTicketTrendChart(res.data.data)
          } else {
            ElMessage.error(res.data.msg || '获取趋势数据失败')
          }
        })
        .catch(err => {
          console.error('获取趋势数据失败:', err)
          ElMessage.error('获取趋势数据失败')
        })
    }
    
    // 获取业务类型分布数据
    const fetchBusinessTypeDistribution = () => {
      const params = {
        startDate: filterForm.dateRange[0],
        endDate: filterForm.dateRange[1],
        windowId: filterForm.windowId || undefined
      }
      
      axios.get('/api/admin/statistics/business-type-distribution', { params })
        .then(res => {
          if (res.data.code === 0) {
            renderBusinessTypeChart(res.data.data)
          } else {
            ElMessage.error(res.data.msg || '获取业务类型分布失败')
          }
        })
        .catch(err => {
          console.error('获取业务类型分布失败:', err)
          ElMessage.error('获取业务类型分布失败')
        })
    }
    
    // 获取等待时间分布数据
    const fetchWaitTimeDistribution = () => {
      const params = {
        startDate: filterForm.dateRange[0],
        endDate: filterForm.dateRange[1],
        businessTypeId: filterForm.businessTypeId || undefined,
        windowId: filterForm.windowId || undefined
      }
      
      axios.get('/api/admin/statistics/wait-time-distribution', { params })
        .then(res => {
          if (res.data.code === 0) {
            renderWaitTimeChart(res.data.data)
          } else {
            ElMessage.error(res.data.msg || '获取等待时间分布失败')
          }
        })
        .catch(err => {
          console.error('获取等待时间分布失败:', err)
          ElMessage.error('获取等待时间分布失败')
        })
    }
    
    // 渲染趋势图
    const renderTicketTrendChart = (data) => {
      if (!ticketTrendChartInstance) {
        ticketTrendChartInstance = echarts.init(ticketTrendChart.value)
      }
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['取号人数', '已服务', '未服务']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.dates || []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '取号人数',
            type: 'line',
            emphasis: {
              focus: 'series'
            },
            data: data.totalTickets || []
          },
          {
            name: '已服务',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: data.servedTickets || []
          },
          {
            name: '未服务',
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            data: data.unservedTickets || []
          }
        ]
      }
      
      ticketTrendChartInstance.setOption(option)
    }
    
    // 渲染业务类型分布图
    const renderBusinessTypeChart = (data) => {
      if (!businessTypeChartInstance) {
        businessTypeChartInstance = echarts.init(businessTypeChart.value)
      }
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: data.map(item => item.name)
        },
        series: [
          {
            name: '业务类型分布',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data.map(item => ({
              name: item.name,
              value: item.count
            }))
          }
        ]
      }
      
      businessTypeChartInstance.setOption(option)
    }
    
    // 渲染等待时间分布图
    const renderWaitTimeChart = (data) => {
      if (!waitTimeChartInstance) {
        waitTimeChartInstance = echarts.init(waitTimeChart.value)
      }
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.timeRanges || []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '人数',
            type: 'bar',
            barWidth: '60%',
            data: data.counts || []
          }
        ]
      }
      
      waitTimeChartInstance.setOption(option)
    }
    
    // 加载所有统计数据
    const loadAllData = () => {
      fetchSummaryData()
      fetchTrendData()
      fetchBusinessTypeDistribution()
      fetchWaitTimeDistribution()
      loadTabData()
    }
    
    // 根据当前选中的标签页加载数据
    const loadTabData = () => {
      switch (activeTab.value) {
        case 'daily':
          fetchDailyData()
          break
        case 'businessType':
          fetchBusinessTypeData()
          break
        case 'window':
          fetchWindowData()
          break
      }
    }
    
    // 处理搜索
    const handleSearch = () => {
      pagination.currentPage = 1
      loadAllData()
    }
    
    // 重置过滤器
    const resetFilter = () => {
      filterForm.businessTypeId = ''
      filterForm.windowId = ''
      filterForm.dateRange = [
        new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        new Date().toISOString().split('T')[0]
      ]
      handleSearch()
    }
    
    // 处理页面大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      loadTabData()
    }
    
    // 处理页码变化
    const handleCurrentChange = (page) => {
      pagination.currentPage = page
      loadTabData()
    }
    
    // 导出Excel
    const exportExcel = () => {
      const params = {
        startDate: filterForm.dateRange[0],
        endDate: filterForm.dateRange[1],
        businessTypeId: filterForm.businessTypeId || undefined,
        windowId: filterForm.windowId || undefined,
        type: activeTab.value
      }
      
      // 构建查询字符串
      const queryParams = new URLSearchParams()
      Object.keys(params).forEach(key => {
        if (params[key] !== undefined) {
          queryParams.append(key, params[key])
        }
      })
      
      // 创建下载链接
      const downloadUrl = `/api/admin/statistics/export?${queryParams.toString()}`
      
      // 创建一个隐藏的a标签来触发下载
      const link = document.createElement('a')
      link.href = downloadUrl
      link.setAttribute('download', `统计报表_${new Date().toISOString().split('T')[0]}.xlsx`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
    
    // 窗口大小变化时重新调整图表大小
    const handleResize = () => {
      if (ticketTrendChartInstance) {
        ticketTrendChartInstance.resize()
      }
      if (businessTypeChartInstance) {
        businessTypeChartInstance.resize()
      }
      if (waitTimeChartInstance) {
        waitTimeChartInstance.resize()
      }
    }
    
    // 监听图表类型变化
    watch(chartType, () => {
      fetchTrendData()
    })
    
    // 监听标签页变化
    watch(activeTab, () => {
      loadTabData()
    })
    
    onMounted(() => {
      fetchBusinessTypes()
      fetchWindows()
      
      // 等待DOM更新后初始化图表
      nextTick(() => {
        loadAllData()
        
        // 添加窗口大小变化监听
        window.addEventListener('resize', handleResize)
      })
    })
    
    return {
      ticketTrendChart,
      businessTypeChart,
      waitTimeChart,
      businessTypes,
      windows,
      filterForm,
      chartType,
      activeTab,
      summaryData,
      dailyData,
      businessTypeData,
      windowData,
      tableLoading,
      pagination,
      formatTime,
      handleSearch,
      resetFilter,
      handleSizeChange,
      handleCurrentChange,
      exportExcel
    }
  }
}
</script>

<style scoped>
.report-container {
  padding: 15px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 22px;
  font-weight: 500;
  color: #303133;
}

.filter-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.04);
}

.statistics-cards {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  text-align: center;
  padding: 10px 0;
}

.charts-container {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart {
  height: 300px;
  width: 100%;
}

.data-table-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.mt-20 {
  margin-top: 20px;
}
</style> 